#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : histogram.py
@Author  : Link
@Time    : 2022/6/4 23:52
@Mark    : 
"""
import math

import numpy as np

from PySide2 import QtWidgets, QtCore
from chart_core.chart_pyqtgraph.utils import CustomViewBox, PlotWidget, InfiniteLine, \
    mkPen, Mixin, graph_range_signal, colormap


class HistogramChart(QtCore.QObject, Mixin):
    """
    类似分布图
    """
    key = None
    li = None

    bins_num = 100  # 在这里表示, 一次show多少颗

    # 选取
    select_start = 0
    select_stop = 0

    # x
    front_data_min = 0
    front_data_max = 0

    list_bins = None
    lines = None  # 线
    unit = ''  # 默认单位

    def __init__(self):
        super(HistogramChart, self).__init__()
        self.vb = CustomViewBox()
        self.pw = PlotWidget(viewBox=self.vb, enableMenu=False)
        self.pw.hideButtons()
        self.pw.addLegend(colCount=2)
        self.bottom_axis = self.pw.getAxis("bottom")
        self.bottom_axis.setHeight(60)
        self.left_axis = self.pw.getAxis("left")
        self.left_axis.setWidth(60)
        self.vb.select_signal.connect(self.select_range)
        self.front_his_dict = dict()
        color = colormap.get('CET-C6')
        self.c = color.getLookupTable(alpha=True)
        self.rota = 0b1010

    def set_data(self, key: str, data_min=None, data_max=None):
        if self.li is None:
            raise Exception("first set li")
        self.key = key
        self.set_title(key)
        self.front_data_min, self.front_data_max = data_min, data_max
        if data_min is None:
            self.front_data_min = self.li.front_df[self.key].min()
        if data_max is None:
            self.front_data_max = self.li.front_df[self.key].max()
        self.bottom_axis.setRange(self.front_data_min, self.front_data_max)

    def select_range(self, ax: QtCore.QRectF):
        pass

    @graph_range_signal
    def set_front_df_chart(self):
        """
        :return:
        """
        if self.key not in self.li.front_df:
            return
        temp_df = self.li.front_df[
            (self.li.front_df[self.key] > self.front_data_min) & (self.li.front_df[self.key] < self.front_data_max)]
        if len(temp_df) == 0:
            return
        self.list_bins = np.linspace(self.front_data_min, self.front_data_max, self.bins_num).round(8)
        for key, each in self.front_his_dict.items():
            each.clear()
        group_item = self.li.front_df.groupby(["GROUP", "DA_GROUP"])
        color_square_nm = math.ceil(pow(len(group_item), 0.5))
        color_split_nm = 512 / 2 ** color_square_nm
        color_list = self.c[::int(color_split_nm)]
        for index, (key, e_df) in enumerate(group_item):
            idx = int(index % color_split_nm)
            y, x = np.histogram(e_df[self.key], bins=self.list_bins)
            temp_key = f"front{key[0]}|{key[1]}"
            if temp_key not in self.front_his_dict:
                color = list(color_list[idx])
                color[3] = 100
                # plot = self.pw.plot(x, y, stepMode="center", fillLevel=-1.7, name=key, brush=color)
                plot = self.pw.plot(x[:-1], y, fillLevel=-0.3, name=key, brush=color)
                self.front_his_dict[temp_key] = plot
            else:
                plot = self.front_his_dict[temp_key]
                plot.setData(x[:-1], y, clear=True)

    @graph_range_signal
    def set_chart_df_chart(self):
        pass

    def full_change_chart(self):
        self.set_front_df_chart()
        self.set_chart_df_chart()
        self.set_line_self()